import Stats from 'three/examples/jsm/libs/stats.module.js'
import { onBeforeUnmount, onMounted, Ref, shallowRef } from 'vue'

export function useStats(statsDomRef: Ref<HTMLDivElement | undefined>) {
  const stats = shallowRef<Stats | null>(null)

  onMounted(() => {
    stats.value = new Stats()
    stats.value.showPanel(0) // 0: fps, 1: ms, 2: mb, 3+: custom
    if (statsDomRef.value) {
      statsDomRef.value.appendChild(stats.value.dom)
    }
    animate()
  })

  onBeforeUnmount(() => {
    if (stats.value && stats.value.dom.parentNode) {
      stats.value.dom.parentNode.removeChild(stats.value.dom)
    }
    stats.value = null
  })

  function animate() {
    if (!stats.value) return
    stats.value.update()
    requestAnimationFrame(animate)
  }

  return {
    stats,
  }
}
